from flask import Blueprint, request, jsonify
import json

bp_goods = Blueprint('good', __name__)
from db import db1


@bp_goods.route('/goodsM', methods=['POST', 'GET', 'DELETE'])
def goodsM():
    if request.method == "POST":
        # 获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造sql语句
        sql = "insert into goods values(0,'%s',%d)" % (data['name'], int(data['cid']))
        # pymsql
        db1.insert(sql)
        # 返回结果
        return 'ok'
    elif request.method == "GET":
        # 展示商品信息（按id倒序、分页、展示分类名称）
        # 获取页面传递过来的当前页,每页面显示多少条
        page = int(request.args.get('page'))
        size = int(request.args.get('size'))
        # 写sql语句,所有的商品信息  left join on
        # 排序 asc升序  desc降序
        start = (page - 1) * size
        # 是否根据分类查询
        cid = int(request.args.get('cid'))
        if cid > 0:
            sql = "select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id where g.cid=%d order by id desc limit %d,%d" % (
            cid, start, size)
            # 查询总条数
            tsql = "select count(id) from goods where cid=%d" % (cid)
        else:
            sql = "select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id order by id desc limit %d,%d" % (
            start, size)
            # 查询总条数
            tsql = "select count(id) from goods"
        res = db1.findall(sql)
        total = db1.find(tsql)
        return jsonify({"code": 200, 'list': res, 'total': total['count(id)']})
    elif request.method == 'DELETE':
        # type为1删除单个,type为2批量删除
        type = int(request.args.get('type'))
        if type == 1:
            # 获取id
            id = int(request.args.get('id'))
            # 构造sql语句
            sql = "delete from goods where id=%d" % (id)
        else:
            ids = request.args.get('id')
            # delete from goods where id in (1,2,3)
            sql = "delete from goods where id in(%s)" % (ids)
        db1.insert(sql)
        # 返回结果
        return jsonify({"code": 200})